package com.example.springdemo.demos.until;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

public class XmlParser {
    public static <T> String toXml(T source) throws Exception {
        //JAXB框架中的API之框架使用上下文对象，要挂载要转换的POJO类.class信息
        JAXBContext context = JAXBContext.newInstance(source.getClass());
        //JAXB框架中的API  数据格式编排转换解析器
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        StringWriter stringWriter = new StringWriter();
        //利用编排解析器转换boy对象使其转换成Xml格式字符串
        marshaller.marshal(source, stringWriter);
        return stringWriter.toString();
    }
    @SuppressWarnings("unchecked")
    public static <T> T parseXml(String xml, Class<T> clazz) throws Exception {
        JAXBContext context = JAXBContext.newInstance(clazz);
        //JAXB框架中的API  数据格式反编排转换解析器
        Unmarshaller unmarshaller = context.createUnmarshaller();
        StringReader stringReader = new StringReader(xml);
        Object obj = unmarshaller.unmarshal(stringReader);
        return (T)obj;
    }
    public static <T> String noneHeaderToXml(T source) throws Exception {
        //JAXB框架中的API之框架使用上下文对象，要挂载要转换的POJO类.class信息
        JAXBContext context = JAXBContext.newInstance(source.getClass());
        //JAXB框架中的API  数据格式编排转换解析器
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        StringWriter stringWriter = new StringWriter();
        //利用编排解析器转换boy对象使其转换成Xml格式字符串
        marshaller.marshal(source, stringWriter);
        return stringWriter.toString();
    }

}
